package com.enmo.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("unchecked")
public class BaseDao<PK extends Serializable,T> {
	
	private SessionFactory sessionFactory;
	private Class<?> entityClazz;
	
	
	public BaseDao(){
		entityClazz = Reflect.getGenericSupperclass(this);
	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	

	//获取Hibernate中的Session
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	public Session getSessionOpen(){
		return sessionFactory.openSession();
	}
	//保存或修改对象
	public void save(T t){
		getSession().saveOrUpdate(t);
	}
	//根据对象删除
	public void del(T t){
		getSession().delete(t);
	}
	//根据ID查找对象
	public T findById(PK id){
		return (T) getSession().get(entityClazz, id);
	}
	//根据ID删除对象
	public void del(PK id){
		getSession().delete(findById(id));
	}
	//获取全部对象
	public List<T> findAll(){
		Criteria cri = getSession().createCriteria(entityClazz);
		return cri.list();
	}
	//根据hql查询对象，返回集合
	public List<T> findByProperty(String hql,Object...params){
		Query query = getSession().createQuery(hql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		return query.list();
	}
	//根据hql查询对象，返回唯一对象
	public T findUniqueResultByProperty(String hql,Object...params){
		Query query = getSession().createQuery(hql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		return (T) query.uniqueResult();
	}
}
